﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CRM.Entity;
using CRM.BLL;
using DP.Web.UI;
using DP.Common;
using System.Text;

namespace CRM.Web.UserManage
{
    public partial class Modify : Common.PageBase
    {

        T_USER_BLL bll = new T_USER_BLL();
        T_BUSINESSDIVISION_BLL bdBll = new T_BUSINESSDIVISION_BLL();
        private T_CONTENTAUTHORITY_BLL caBll = new T_CONTENTAUTHORITY_BLL();
        T_MARKETDEPARTMENT_BLL marketDepartmentBll = new T_MARKETDEPARTMENT_BLL();
        private T_DEALER_BLL dealerBll = new T_DEALER_BLL();
        private T_SERVICEPROVIDER_BLL serviceProviderBll = new T_SERVICEPROVIDER_BLL();
        private T_SUPPLIER_BLL supplierBll = new T_SUPPLIER_BLL();
        T_DEPARTMENT_BLL departmentbll = new T_DEPARTMENT_BLL();

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PageHelper.SetPrePageUrl(this.Page);
           
            PageHelper.SetGoBackUrl(this.Page, btnCancel, StaticConstant.NotBackUrl);
            PageHelper.SetPopCalender(this.Page, txtBIRTHDATE);
            //PageHelper.SetPopCalender(this.Page, txtCREATETIME);
            //PageHelper.SetPopCalender(this.Page, txtLASTMODIFYTIME);

        }

        public string InitChineseUrl(string chineseUrl)
        {
            Uri url = new Uri(chineseUrl);
            System.Collections.Specialized.NameValueCollection nv = System.Web.HttpUtility.ParseQueryString(url.Query, System.Text.Encoding.GetEncoding("utf-8"));
            string query = "";
            for (int i = 0; i < nv.Count; i++)
            {
                if (query.Trim() == string.Empty)
                {
                    query = "?" + nv.Keys[i] + "=" + HttpUtility.UrlEncode(nv[i], System.Text.Encoding.GetEncoding("utf-8"));
                }
                else
                {
                    query += "&" + nv.Keys[i] + "=" + HttpUtility.UrlEncode(nv[i], System.Text.Encoding.GetEncoding("utf-8"));
                }
            }
            string u = chineseUrl.Split('?')[0] + query;
            return u;
        } 

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlUserTypeBinding();
                ddlBUSINESSDIVISIONIDBinding();
                ddlBUSINESSDIVISIONID_SelectedIndexChanged(null, null);
                ddlDEPARTMENTIDBinding();
                ddlROLEIDBinding(); 
                ddlGENDERBinding();
                ddlSTATUSBinding();
                ddlLOCKEDBinding();

                pageDataInit();
            }
        }

     

        #region 页面初始化数据绑定


        /// <summary>
        /// DDLs the user type binding.
        /// </summary>
        private void ddlUserTypeBinding()
        {
            ddlUserType.Items.Clear();
            EnumHelper.FillListControl(ddlUserType, typeof (UserType));
        }


        /// <summary>
        ///	部门编号 下拉列表数据绑定
        /// </summary>
        private void ddlDEPARTMENTIDBinding()
        {
            string businessDivisionCode = string.Empty;
            T_BUSINESSDIVISION_Entity bdEntity =
                bdBll.GetCache_T_BUSINESSDIVISION_EntityByKey(this.Page, StringHelper.ToInt(ddlBUSINESSDIVISIONID.SelectedValue.Trim()));
            if (bdEntity != null)
            {
                businessDivisionCode = bdEntity.BUSINESSDIVISIONCODE;
            }

            switch ((UserType) Enum.Parse(typeof (UserType), ddlUserType.SelectedValue))
            {
                case UserType.中心部门:
                    {
                        departmentbll.FillListControl(ddlDEPARTMENTID, "0", businessDivisionCode, "");
                        ddlDEPARTMENTIDTwo.DataSource = departmentbll.GetList(String.Format(" and BUSINESSDIVISIONCODE = '{0}' ", businessDivisionCode));
                        ddlDEPARTMENTIDTwo.DataTextField = "DepartmentCode";
                        ddlDEPARTMENTIDTwo.DataValueField = "DepartmentID";
                        ddlDEPARTMENTIDTwo.DataBind();
                        ddlDEPARTMENTID.Items.Insert(0, new ListItem("", ""));
                        ddlDEPARTMENTIDTwo.Items.Insert(0, new ListItem("",""));
                    }
                    break;
                case UserType.供应商:
                    {
                        //var list = supplierBll.GetList(String.Format(" and BUSINESSDIVISIONCODE = '{0}' ", businessDivisionCode));
                        var list = supplierBll.GetList(String.Format(" and BUSINESSDIVISIONCODE = '{0}' ", businessDivisionCode), " SUPPLIERNAME asc ")
                                .Select(p => new
                                {
                                    SupplierName = (p.SUPPLIERNAME.Length > 0) ? StringHelper.GetChineseSpell(p.SUPPLIERNAME)[0].ToString() + "-" + p.SUPPLIERNAME : p.SUPPLIERNAME,
                                    SupplierID = p.SUPPLIERID,
                                    SupplierCode = p.SUPPLIERCODE
                                });
                        ddlDEPARTMENTID.DataSource = list;
                        ddlDEPARTMENTID.DataTextField = "SupplierName";
                        ddlDEPARTMENTID.DataValueField = "SupplierID";
                        ddlDEPARTMENTID.DataBind();
                        ddlDEPARTMENTIDTwo.DataSource = list;
                        ddlDEPARTMENTIDTwo.DataTextField = "SupplierCode";
                        ddlDEPARTMENTIDTwo.DataValueField = "SupplierID";
                        ddlDEPARTMENTIDTwo.DataBind();
                        ddlDEPARTMENTID.Items.Insert(0, new ListItem("", ""));
                        ddlDEPARTMENTIDTwo.Items.Insert(0, new ListItem("", ""));

                    }
                    break;
                case UserType.市场部:
                    {
                        //var list = marketDepartmentBll.GetList(String.Format(" and BUSINESSDIVISIONCODE = '{0}' ", businessDivisionCode));
                        var list = marketDepartmentBll.GetList(String.Format(" and BUSINESSDIVISIONCODE = '{0}' ", businessDivisionCode), " MARKETDEPARTMENTNAME asc ")
                           .Select(p => new
                           {
                               MarketDepartmentName = (p.MARKETDEPARTMENTNAME.Length > 0) ? StringHelper.GetChineseSpell(p.MARKETDEPARTMENTNAME)[0].ToString() + "-" + p.MARKETDEPARTMENTNAME : p.MARKETDEPARTMENTNAME,
                               MarketDepartmentID = p.MARKETDEPARTMENTID,
                               MarketDepartmentCode = p.MARKETDEPARTMENTCODE
                           });
                        ddlDEPARTMENTID.DataSource = list;
                        ddlDEPARTMENTID.DataTextField = "MarketDepartmentName";
                        ddlDEPARTMENTID.DataValueField = "MarketDepartmentID";
                        ddlDEPARTMENTID.DataBind();
                        ddlDEPARTMENTIDTwo.DataSource = list;
                        ddlDEPARTMENTIDTwo.DataTextField = "MarketDepartmentCode";
                        ddlDEPARTMENTIDTwo.DataValueField = "MarketDepartmentID";
                        ddlDEPARTMENTIDTwo.DataBind();
                        ddlDEPARTMENTID.Items.Insert(0, new ListItem("", ""));
                        ddlDEPARTMENTIDTwo.Items.Insert(0, new ListItem("", ""));
                    }
                    break;
                case UserType.服务商:
                    {
                        //var list = serviceProviderBll.GetList(String.Format(" and BUSINESSDIVISIONCODE = '{0}' ", businessDivisionCode));
                        var list = serviceProviderBll.GetList(String.Format(" and BUSINESSDIVISIONCODE = '{0}'  ", businessDivisionCode), " SERVICEPROVIDERNAME asc ")
                            .Select(p => new
                            {
                                ServiceProviderName = (p.SERVICEPROVIDERNAME.Length > 0) ? StringHelper.GetChineseSpell(p.SERVICEPROVIDERNAME)[0].ToString() + "-" + p.SERVICEPROVIDERNAME : p.SERVICEPROVIDERNAME,
                                ServiceProviderID = p.SERVICEPROVIDERID,
                                ServiceProviderCode = p.SERVICEPROVIDERCODE
                            });
                        ddlDEPARTMENTID.DataSource = list;
                        ddlDEPARTMENTID.DataTextField = "ServiceProviderName";
                        ddlDEPARTMENTID.DataValueField = "ServiceProviderID";
                        ddlDEPARTMENTID.DataBind();
                        ddlDEPARTMENTIDTwo.DataSource = list;
                        ddlDEPARTMENTIDTwo.DataTextField = "ServiceProviderCode";
                        ddlDEPARTMENTIDTwo.DataValueField = "ServiceProviderID";
                        ddlDEPARTMENTIDTwo.DataBind();
                        ddlDEPARTMENTID.Items.Insert(0, new ListItem("", ""));
                        ddlDEPARTMENTIDTwo.Items.Insert(0, new ListItem("", ""));
                    }
                    break;
                case UserType.经销商:
                    {
                        //var list = dealerBll.GetList(String.Format(" and BUSINESSDIVISIONCODE = '{0}' ", businessDivisionCode));
                        var list = dealerBll.GetList(String.Format(" and BUSINESSDIVISIONCODE = '{0}'  ", businessDivisionCode), " DEALERNAME asc ")
                            .Select(p => new
                            {
                                DealerName = (p.DEALERNAME.Length > 0) ? StringHelper.GetChineseSpell(p.DEALERNAME)[0].ToString() + "-" + p.DEALERNAME : p.DEALERNAME,
                                DealerID = p.DEALERID,
                                DealerCode = p.DEALERCODE
                            });
                        ddlDEPARTMENTID.DataSource = list;
                        ddlDEPARTMENTID.DataTextField = "DealerName";
                        ddlDEPARTMENTID.DataValueField = "DealerID";
                        ddlDEPARTMENTID.DataBind();
                        ddlDEPARTMENTIDTwo.DataSource = list;
                        ddlDEPARTMENTIDTwo.DataTextField = "DealerCode";
                        ddlDEPARTMENTIDTwo.DataValueField = "DealerID";
                        ddlDEPARTMENTIDTwo.DataBind();
                        ddlDEPARTMENTID.Items.Insert(0, new ListItem("", ""));
                        ddlDEPARTMENTIDTwo.Items.Insert(0, new ListItem("", ""));
                    }
                    break;
                default:
                    {

                    }
                    break;
            }
            txtSEATID.Enabled = false;
        }



        /// <summary>
        ///	角色编号 下拉列表数据绑定
        /// </summary>
        private void ddlROLEIDBinding()
        {
            string businessDivisionCode = string.Empty;
            T_BUSINESSDIVISION_Entity bdEntity = bdBll.GetCache_T_BUSINESSDIVISION_EntityByKey(this.Page, StringHelper.ToInt(ddlBUSINESSDIVISIONID.SelectedValue.Trim()));
            if(bdEntity != null)
            {
                businessDivisionCode = bdEntity.BUSINESSDIVISIONCODE;
            }
            T_ROLE_BLL bll = new T_ROLE_BLL();
            ddlROLEID.DataSource = bll.GetList(string.Format(" and BUSINESSDIVISIONCODE = '{0}' ", businessDivisionCode));
            ddlROLEID.DataTextField = "RoleName";
            ddlROLEID.DataValueField = "RoleID";
            ddlROLEID.DataBind();
            //ddlROLEID.Items.Insert(0, new ListItem("", ""));
        }

        private void ddlGENDERBinding()
        {
            ddlGENDER.Items.Clear();
            EnumHelper.FillListControl(ddlGENDER, typeof(Gender));
        }

        private void ddlLOCKEDBinding()
        {
            ddlLOCKED.Items.Clear();
            EnumHelper.FillListControl(ddlLOCKED, typeof(IsLocked));
        }

        private void ddlSTATUSBinding()
        {
            ddlSTATUS.Items.Clear();
            EnumHelper.FillListControl(ddlSTATUS, typeof(Status));
        }



        private void ddlBUSINESSDIVISIONIDBinding()
        {
            ddlBUSINESSDIVISIONID.DataSource = bdBll.GetCacheList(this.Page, String.Format(" and Status = {0} ", ((int)Status.启用).ToString()), "Status");
            ddlBUSINESSDIVISIONID.DataTextField = "BUSINESSDIVISIONNAME";
            ddlBUSINESSDIVISIONID.DataValueField = "BUSINESSDIVISIONID";
            ddlBUSINESSDIVISIONID.DataBind();

            if (!UserLoginInfo.IsAdministrator())
            {
                ddlBUSINESSDIVISIONID.SelectedValue = _userLoginInfo.UserEntity.BUSINESSDIVISIONID.ToString();
                ddlBUSINESSDIVISIONID.Enabled = false;
            }

        }


     


















        #endregion

        private void pageDataInit()
        {
            string _userid = String.IsNullOrEmpty(Request.QueryString["USERID"]) ? "" : Request.QueryString["USERID"].Trim();

            if (!String.IsNullOrEmpty(_userid))
            {
                T_USER_Entity entity = bll.GetEntity("USERID", _userid);

                ddlBUSINESSDIVISIONID.SelectedValue = entity.BUSINESSDIVISIONID.ToString();
                ddlUserType.SelectedValue = entity.USERTYPE.Trim();
                ddlBUSINESSDIVISIONID_SelectedIndexChanged(null, null);
                ddlROLEID.SelectedValue = entity.ROLEID.ToString();
                try
                {
                    ddlDEPARTMENTID.SelectedValue = entity.DEPARTMENTID.ToString();
                }
                catch (Exception ex)
                {

                }

                PageHelper.SetControlValue<T_USER_Entity>(this.Page, entity);
                
                if (entity.BIRTHDATE != null)
                {
                    txtBIRTHDATE.Text = entity.BIRTHDATE.Value.ToString("yyyy-MM-dd");
                }
                lblTitle.Text = "用户修改";
            }
            else
            {
                lblTitle.Text = "用户添加";

            }
            txtCREATEPEOPLE.Enabled = false;
            //txtCREATEPEOPLEID.Enabled = false;
            txtCREATETIME.Enabled = false;
            txtLASTMODIFYPEOPLE.Enabled = false;
            //txtLASTMODIFYPEOPLEID.Enabled = false;
            txtLASTMODIFYTIME.Enabled = false;
            if (!UserLoginInfo.IsAdministrator())
            {
                ddlBUSINESSDIVISIONID.SelectedValue = _userLoginInfo.UserEntity.BUSINESSDIVISIONID.ToString();
                ddlBUSINESSDIVISIONID.Enabled = false;
            }

        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            string _userid = String.IsNullOrEmpty(Request.QueryString["USERID"]) ? "" : Request.QueryString["USERID"].Trim();


            T_USER_Entity entity = bll.GetEntity("USERID", _userid);

            if (entity != null)
            {
                PageHelper.GetControlValue<T_USER_Entity>(this.Page, ref entity);
                entity.LASTMODIFYPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                entity.LASTMODIFYPEOPLEID = _userLoginInfo.UserEntity.USERID;
                entity.LASTMODIFYTIME = DateTime.Now;
                try
                {
                    entity.ROLENAME = ddlROLEID.SelectedItem.Text;
                }catch
                {
                }
                try
                {
                    entity.DEPARTMENTNAME = ddlDEPARTMENTID.SelectedItem.Text.Trim();
                }catch
                {
                }
                
                ddlDEPARTMENTIDTwo.SelectedValue = ddlDEPARTMENTID.SelectedValue;
                try
                {
                    entity.DEPARTMENTCODE = ddlDEPARTMENTIDTwo.SelectedItem.Text;
                }
                catch
                {
                }
                T_BUSINESSDIVISION_Entity bdEntity = bdBll.GetCache_T_BUSINESSDIVISION_EntityByKey(this.Page, StringHelper.ToInt(ddlBUSINESSDIVISIONID.SelectedValue.Trim()));
                if (bdEntity != null)
                {
                    entity.BUSINESSDIVISIONCODE = bdEntity.BUSINESSDIVISIONCODE;
                    entity.BUSINESSDIVISIONNAME = bdEntity.BUSINESSDIVISIONNAME;
                }


                try
                {

                    long rel = bll.Update(entity);
                    if (rel > 0)
                    {
                        PageHelper.ShowMessage(this.Page, "修改成功！", UserLoginInfo.FilterBackUrl(PageHelper.GetPrePageUrl(this), "list.aspx"));
                    }
                    else
                    {
                        PageHelper.ShowMessage(this.Page, "修改失败！");
                    }
                }
                catch (Exception ex)
                {
                        PageHelper.ShowMessage(this.Page, "修改失败！" + ex.Message);
                }
            }
            else
            {
                entity = new T_USER_Entity();

                PageHelper.GetControlValue<T_USER_Entity>(this.Page, ref entity);
                entity.PASSWORD = UserLoginInfo.PasswordEncryption(configBll.GetCacheValueByName(this.Page, "DefaultPassword"));
                entity.CREATEPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                entity.CREATEPEOPLEID = _userLoginInfo.UserEntity.USERID;
                entity.CREATETIME = DateTime.Now;
                entity.LASTMODIFYPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                entity.LASTMODIFYPEOPLEID = _userLoginInfo.UserEntity.USERID;
                entity.LASTMODIFYTIME = DateTime.Now;
                try
                {
                    entity.ROLENAME = ddlROLEID.SelectedItem.Text;
                }catch
                {
                }
                try
                {
                    entity.DEPARTMENTNAME = ddlDEPARTMENTID.SelectedItem.Text.Trim();
                }catch
                {
                }
                ddlDEPARTMENTIDTwo.SelectedValue = ddlDEPARTMENTID.SelectedValue;
                try
                {
                    entity.DEPARTMENTCODE = ddlDEPARTMENTIDTwo.SelectedItem.Text;
                }catch
                {
                }
                T_BUSINESSDIVISION_Entity bdEntity = bdBll.GetCache_T_BUSINESSDIVISION_EntityByKey(this.Page, StringHelper.ToInt(ddlBUSINESSDIVISIONID.SelectedValue.Trim()));
                if (bdEntity != null)
                {
                    entity.BUSINESSDIVISIONCODE = bdEntity.BUSINESSDIVISIONCODE;
                    entity.BUSINESSDIVISIONNAME = bdEntity.BUSINESSDIVISIONNAME;
                }


                try
                {
                    long rel = bll.Insert(entity);
                    if (rel > 0)
                    {
                        caBll.SetUserContentAuthority(entity);
                        PageHelper.ShowMessage(this.Page, "添加成功！", "list.aspx");
                    }
                    else
                    {
                        PageHelper.ShowMessage(this.Page, "添加失改！");
                    }
                }
                catch (Exception ex)
                {
                    
                        PageHelper.ShowMessage(this.Page, "添加失改！" + ex.Message);
                }

            }
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlBUSINESSDIVISIONID control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ddlBUSINESSDIVISIONID_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlDEPARTMENTIDBinding();
            ddlROLEIDBinding(); 
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlUserType control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ddlUserType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlDEPARTMENTIDBinding();
        }
    }
}
